import { onHide, onShow } from '@dcloudio/uni-app';
import { nanoid } from 'nanoid';
import { BooleanNumber } from '@/enums';
import { useUserStore } from '@/store/userStore';
import { downloadToDir } from '@/utils/download.utils';
import { isApp } from '@/utils/platform.utils';

// enum PRINT_MODE {
//   // 标签
//   LABEL = 1,
//   // 票据
//   TICKET = 2
// }

interface PrinterConfig {
  pluginName: string
  downloadDir: string
  initMethod: string
}

function createThermalPrinter(config: PrinterConfig) {
  let thermalPrinter;
  // #ifdef APP-PLUS
  // eslint-disable-next-line prefer-const
  thermalPrinter = uni.requireNativePlugin(config.pluginName);
  console.log('>>>thermalPrinter', thermalPrinter);
  // #endif

  const { getAuthStore } = useUserStore();

  const initPrinter = () => {
    thermalPrinter[config.initMethod](res => {
      if (res.success === BooleanNumber.TRUE) {
        console.log('>>>>热敏打印机初始化成功', res);
        // TODO 缺少获取当前打印模式的方法
        // thermalPrinter.setMode(PRINT_MODE.TICKET, res => {
        //   console.log('>>>>设置热敏打印模式', res);
        // });
      }
      else {
        console.error('>>>>热敏打印机初始化失败', res);
      }
    });
  };

  const print = (url: string) => {
    const fileName = `${nanoid()}.png`;
    console.log('>>>file', fileName);
    const headers = {
      Authorization: `Bearer ${getAuthStore().accessToken}`
    };
    return downloadToDir(url, fileName, config.downloadDir, headers).then(() => {
      return new Promise((resolve, reject) => {
        thermalPrinter.print(fileName, res => {
          console.log('>>>>热敏机打印结果', res);

          if (res.success === BooleanNumber.TRUE) {
            resolve(res);
          }
          else {
            uni.showModal({
              title: '操作失败',
              content: res.data,
              showCancel: false
            });
            reject(res);
          }
        });
      });
    });
  };

  onShow(() => {
    if (isApp) {
      initPrinter();
    }
  });

  onHide(() => {
    if (isApp) {
      thermalPrinter.free();
    }
  });

  return {
    print,
    initPrinter
  };
}

/**
 * EM30L热敏打印机钩子
 */
export function useThermalPrinterEM30L() {
  return createThermalPrinter({
    pluginName: 'XWC-Printer-EM30L',
    downloadDir: '/XYC/EM30L',
    initMethod: 'initPrinterEM30L'
  });
}

/**
 * EM5826热敏打印机钩子
 */
export function useThermalPrinterEM5826() {
  return createThermalPrinter({
    pluginName: 'XWC-Printer-EM5826',
    downloadDir: '/XYC/EM5826',
    initMethod: 'initPrinterEM5826'
  });
}

export enum THERMAL_PRINTER_TYPE {
  /**
   * 80mm 挂号缴费凭条
   */
  EM30L,
  /**
   * 30mm 签到凭条
   */
  EM5826
}

export function useThermalPrinter(type: THERMAL_PRINTER_TYPE = THERMAL_PRINTER_TYPE.EM30L) {
  if (type === THERMAL_PRINTER_TYPE.EM30L) {
    return useThermalPrinterEM30L();
  }
  else {
    return useThermalPrinterEM5826();
  }
}
